/***************************************************************************
 *   Copyright (C) 2007 by Luca Bellonda                                   *
 *   lbell @ tsc4.com                                                      *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
/*
 * Deve funzionare cosi': faccio partire un servizio per rinfrescare i feed
 * ogni n minuti. Il servizio al ricevimento di novita' fa comparire un'icona
 * e scrive su database i feeds (titolo, data, letto ed autore), come pure id
 * dell'ultimo letto.
 */

package lb.prove;

import lb.prove.R;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.DeadObjectException;
import android.os.IBinder;
import android.view.Menu;
import android.view.SubMenu;
import android.view.View;
import android.view.Menu.Item;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

public class PlanetFeedsRead extends Activity {

	final int IdEmpty = 1;
	final int ACTIVITY_RSSDET = 0;
	final int ACTIVITY_SETTIMEOUT=1;
	final int ACTIVITY_SETNEWURL=2;
	
	public static final String KEY_ITEM = "item" ;
	public static final String KEY_TITLE = "title" ;
	public static final String KEY_BODY = "body" ;
	public static final String KEY_PUBDATE = "pubdate" ;
	public static final String KEY_URL = "url" ;
	public static final String KEY_MINVAL="minval";
	public static final String KEY_MAXVAL="maxval";
	public static final String KEY_ISNUMBER="isnumb";
	public static final String KEY_INITIALVALUE="initval";
	public static final String KEY_DEFAULTVALUE="defval";
	public static final String KEY_RETURNVALUE="retval";

    static final int MIN_INTERVAL_MINUTES = 10;
    static final int MAX_INTERVAL_MINUTES = 120;
    static final String MIN_INTERVAL_MINUTES_STR="120";
	
	private NotificationManager	mNotificationManager;
	private RSSAdapter itemsAdapter;
	
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
    	mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

        setContentView(R.layout.main);

        ListView theList = getRssView();
        TextView tv = new TextView(this);
        tv.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        tv.setText(R.string.reading);
        theList.setEmptyView(tv);
        setVoidListAdapter(theList);
        theList.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
        	public void onItemClick( AdapterView parent, View v, int position, long id){
        		myItemClick(parent, v, position, id);}
        	});
        startOperations();
        fillRSS(theList);        
    }
    @Override
    protected void onPause() {
        super.onPause();
        if (dbHelper != null) {
        	dbHelper.close();
        	dbHelper = null;
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        if (dbHelper == null) {
            dbHelper = new DBHelper(this);
        }
        fillRSS(getRssView());
    }
    @Override
    public void onDestroy()
    {
    	unbindService();
        stopService(new Intent(PlanetFeedsRead.this, ReadRSSService.class));
    	if(null!=mNotificationManager)
    		mNotificationManager.cancel(R.string.srv_new_feeds);
        super.onDestroy();
    }
    ListView getRssView()
    {
    	return (ListView) findViewById(R.id.rssList);
    }
    public static final int M_AGG = Menu.FIRST;
    public static final int M_DET = Menu.FIRST+1;
    public static final int M_DEL = Menu.FIRST+2;
    public static final int M_CHG_UPDT = Menu.FIRST+3;
    public static final int M_CHG_DELINT = Menu.FIRST+4;
    public static final int M_DEL_ALL = Menu.FIRST+5;
    public static final int M_SRV_PAUSE = Menu.FIRST+6;
    public static final int M_SRV_RESUME = Menu.FIRST+7;
    public static final int M_SRV_CHGSRC = Menu.FIRST+8;
    public static final int M_CREDITS = Menu.FIRST+9;
    public static final int M_READHTML = Menu.FIRST+10;
    public static final int M_SRV_CHGINT = Menu.FIRST+11;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        boolean result = super.onCreateOptionsMenu(menu);

        menu.add(0, M_AGG, R.string.menu_agg);
        menu.add(0, M_DET, R.string.menu_det);
        menu.add(0, M_READHTML, R.string.menu_dethtml);
        menu.addSeparator(0,0);
        menu.add(0, M_DEL, R.string.menu_del);
        menu.addSeparator(0,0);
        ////menu.add(0, M_CHG_UPDT, R.string.menu_chg_upd);
        ///menu.add(0, M_CHG_DELINT, R.string.menu_chg_del_int);
        menu.add(0, M_DEL_ALL, R.string.menu_del_all);
        SubMenu subMenu = menu.addSubMenu(0, 0, R.string.menu_submenu_srv);
        //subMenu.add(0, M_SRV_PAUSE, R.string.menu_srv_pause);
        //subMenu.add(0, M_SRV_RESUME, R.string.menu_srv_resume);
        //subMenu.addSeparator(0,0);
        subMenu.add(0, M_SRV_CHGSRC, R.string.menu_chg_src);
        subMenu.add(0, M_SRV_CHGINT, R.string.menu_chg_int);
        menu.add(0, M_CREDITS, R.string.menu_credits);
        
        return result;
    }
    void myItemClick(AdapterView parent, View v, int position, long id)
    {
    	//super.onItemClick(parent, v, position, id);
        Intent i = new Intent(this, ItemDetails.class);
        RssItem item = itemsAdapter.getRssItem(position);
        if((null==item)||(item.isDate))
        	return;
        if(null!=dbHelper)
        	dbHelper.markRead(item.guid);
        i.putExtra(KEY_ITEM,item.guid);
        i.putExtra(KEY_TITLE,item.title);
        i.putExtra(KEY_BODY,item.body);
        i.putExtra(KEY_PUBDATE,item.pubDate);
        startSubActivity(i, ACTIVITY_RSSDET);
    }
    @Override
    public boolean onMenuItemSelected(int featureId, Item item) {
        super.onMenuItemSelected(featureId, item);
        switch(item.getId()) {
        case M_AGG:
        	onMenuAgg();
            break;
        case M_DEL:
        	onDeleteItem();
        	break;
        case M_DEL_ALL:
        	onDeleteItems();
        	break;
        case M_CREDITS:
        	displayCredits();
        	break;
        case M_READHTML:
        	displayAsHtml();
        	break;
        case M_SRV_CHGSRC:
        	changeUrl();
        	break;
        case M_SRV_CHGINT:
        	changeInterval();
        	break;
        }
        return true;
    }
    void onMenuAgg() {
    	rescanEntries();
    }
    void onDeleteItem()
    {
    	ListView L = getRssView();
    	if( null == L )
    		return ;
    	int index = L.getSelectedItemIndex();
    	if( (index>=0) && (index<L.getCount()) )
    	{
    		RssItem rssItem = itemsAdapter.getRssItem(index);
    		if((null!=rssItem)&&(rssItem.guid!=null))
    			dbHelper.deleteItem(rssItem.guid);
    	}
    	rescanEntries();
    }
    void onDeleteItems()
    {
    	dbHelper.deleteItems();
    	rescanEntries();
    }
    void displayAsHtml()
    {
    	ListView L = getRssView();
    	if( null == L )
    		return ;
    	int index = L.getSelectedItemIndex();
    	if( (index>=0) && (index<L.getCount()) )
    	{
    		RssItem rssItem = itemsAdapter.getRssItem(index);
    		if((null!=rssItem)&&(rssItem.guid!=null))
    		{
    	        Intent i = new Intent(this, ItemHTML.class);
    	        if(null!=dbHelper)
    	        	dbHelper.markRead(rssItem.guid);
    	        i.putExtra(KEY_URL, rssItem.url);
    	        startSubActivity(i, ACTIVITY_RSSDET);
    		}
    	}
    }
    void changeUrl()
    {
        Intent i = new Intent(this, AskUser.class);
        i.putExtra(KEY_TITLE, getText(R.string.title_change_url));
        i.putExtra(KEY_ISNUMBER,new Boolean(false));
        i.putExtra(KEY_INITIALVALUE,ReadRSSService.URL_DEFAULT);
        i.putExtra(KEY_DEFAULTVALUE,ReadRSSService.URL_DEFAULT);
        
        startSubActivity(i, ACTIVITY_SETNEWURL);
    }
    void changeInterval()
    {
        Intent i = new Intent(this, AskUser.class);
        i.putExtra(KEY_TITLE, getText(R.string.title_change_interval));
        i.putExtra(KEY_MINVAL, new Integer(MIN_INTERVAL_MINUTES));
        i.putExtra(KEY_MAXVAL, new Integer(MAX_INTERVAL_MINUTES));
        i.putExtra(KEY_ISNUMBER,new Boolean(false));
        i.putExtra(KEY_INITIALVALUE, MIN_INTERVAL_MINUTES_STR);
        i.putExtra(KEY_DEFAULTVALUE, MIN_INTERVAL_MINUTES_STR);
        
        startSubActivity(i, ACTIVITY_SETNEWURL);
    }
    void displayCredits()
    {
    	showAlert(getText(R.string.credits_title), getText(R.string.credits_text), getText(R.string.butt_close), null, false, null);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, String data, Bundle extras) {
    	super.onActivityResult(requestCode, resultCode, data, extras);
    	if(resultCode!=RESULT_OK)
    		return;
        try
        {
	        switch(requestCode) {
	        	case ACTIVITY_SETTIMEOUT:
	        	{
	        		int retValue = extras.getInteger(PlanetFeedsRead.KEY_RETURNVALUE);
	        		setServiceTimeout(retValue);
	        	}
	            break;
	        	case ACTIVITY_SETNEWURL:
	        	{
	        		String retValue = extras.getString(PlanetFeedsRead.KEY_RETURNVALUE);
	        		setServiceUrl(retValue);
	        	}
	        	break;
	        }
        }catch (Exception e) {
        	errorOp();
		}
    }
    void errorOp()
    {
    	showAlert(getText(R.string.app_name), getText(R.string.error_op), getText(R.string.butt_close), null, false, null);
    }
    @Override
    public boolean onOptionsItemSelected(Item item) {
        switch (item.getId()) {
        case M_AGG:
            rescanEntries();
            break;
        }
        return super.onOptionsItemSelected(item);
    }
    void rescanEntries()
    {
    	if(null!=mNotificationManager)
    		mNotificationManager.cancel(R.string.srv_new_feeds);
    	fillRSS(getRssView());
    }
    private void setVoidListAdapter(ListView theList) {
        ArrayList<String> sList = new ArrayList<String>(); 
        ArrayAdapter<String> meVoid = 
        	new ArrayAdapter<String>(this, R.layout.rss_row, sList);
        theList.setAdapter(meVoid);
    }
	DBHelper dbHelper;
    private void startOperations()
    {
    	dbHelper = new DBHelper(this);

    	Bundle args = new Bundle();
        args.putLong("readTimeout", 0l);
        dbHelper.addEntry("id", "prova", "jsnsd adn ad kja nkjansd ajk", "", new Date(), "http://");
        startService( new Intent(PlanetFeedsRead.this,ReadRSSService.class), args);
        bindToService();
    }
    private void fillRSS(ListView rssList) {
    	// scan database
    	// build list array
    	List<RssItem> items = dbHelper.fetchAllRows();
    	itemsAdapter = new RSSAdapter(this, items);
        rssList.setAdapter(itemsAdapter);
    }

	IReadService mService= null;
    private ServiceConnection mServiceConnection = new ServiceConnection()
    {
        public void onServiceConnected(ComponentName className, IBinder service)
        {
        	mService = IReadService.Stub.asInterface(service);
        }

        public void onServiceDisconnected(ComponentName className)
        {
        	mService = null;
        }
    };
    void bindToService()
    {
   		bindService(new Intent(PlanetFeedsRead.this, ReadRSSService.class), 
                    null, mServiceConnection, Context.BIND_AUTO_CREATE );
    }
    void unbindService()
    {
    	unbindService(mServiceConnection);
    }
    void setServiceTimeout(final int newTimeout) throws DeadObjectException
    {
		if(null!=mService)
			mService.setReadTimeout(newTimeout);
    }
    void setServiceUrl(final String newUrl) throws DeadObjectException
    {
   		if(null!=mService)
   			mService.setUrl(newUrl);
    }
}